package com.hefei.garden.config.netty.server;

import com.hefei.garden.config.netty.handler.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * @author: yxchen6
 * @date: 2022/7/24 14:52
 * @description:
 */
@Component
@Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Autowired(required = false)
    @Qualifier("closeFutureHandler")
    public Handler closeFutureHandler;

    @Autowired(required = false)
    @Qualifier("exceptionFutureHandler")
    public Handler exceptionFutureHandler;

    @Autowired
    @Qualifier("businessFutureHandler")
    public Handler businessFutureHandler;

    @Override
    protected void channelRead0(ChannelHandlerContext context, ByteBuf msg) {
        String retMsg = businessFutureHandler.handler(msg.toString(CharsetUtil.UTF_8));
        context.writeAndFlush(retMsg);
        context.fireChannelRead(msg);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext context) {
        String text = context.channel().id().asLongText();
        System.out.println(text);
        System.out.println(context.channel().remoteAddress() + "channelRegistered");
    }

    @Override
    public void channelActive(ChannelHandlerContext context) {
        System.out.println(context.channel().remoteAddress() + "channelActive");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext context) throws Exception {
        System.out.println(context.channel().remoteAddress() + " channelUnregistered ");
        super.channelUnregistered(context);
        if (closeFutureHandler != null) {
            closeFutureHandler.handler(context.name());
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext context) {
        System.out.println(context.channel().remoteAddress() + "channelInactive");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " exceptionCaught :" + cause.getMessage());
        super.exceptionCaught(ctx, cause);
        if (exceptionFutureHandler != null) {
            exceptionFutureHandler.handler(cause.getMessage());
        }
    }

}


